Promise.prototype.finally = function(callback) {
  let P = this.constructor;
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason =>
      P.resolve(callback()).then(() => {
        throw reason;
      })
  );
};

// 教师的小标签
const teacherTagStyles = [
  { name: '', type: '' },
  { name: '小学', type: 'primary' },
  { name: '初中', type: 'junior' },
  { name: '高中', type: 'senior' }
];

//封装异步api
const wxPromisify = fn => {
  return function(obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function(res) {
        resolve(res);
      };

      obj.fail = function(res) {
        reject(res);
      };

      fn(obj);
    });
  };
};

const getRequestPromisified = wxPromisify(wx.request);

// 封装post请求
const post = (url, data) => {
  var promise = new Promise((resolve, reject) => {
    //网络请求
    wx.request({
      url: url,
      data: data,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        token: wx.getStorageSync('token')
      },
      success: function(res) {
        //服务器返回数据
        if (res.statusCode == 200) {
          resolve(res);
        } else {
          //返回错误提示信息
          reject(res.data);
        }
      },
      error: function(e) {
        reject('网络出错');
      }
    });
  });
  return promise;
};
// 封装get请求
const get = (url, data) => {
  var promise = new Promise((resolve, reject) => {
    //网络请求
    wx.request({
      url: url,
      data: data,
      header: {
        'content-type': 'application/json',
        token: wx.getStorageSync('token')
      },
      success: function(res) {
        //服务器返回数据
        if (res.statusCode == 200) {
          resolve(res);
        } else {
          //返回错误提示信息
          reject(res.data);
        }
      },
      error: function(e) {
        reject('网络出错');
      }
    });
  });
  return promise;
};

const formatDate = now_time => {
  var date = new Date(now_time);
  var dt =
    date.getFullYear() +
    '-' +
    (date.getMonth() < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) +
    '-' +
    (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  return dt;
};

const formatTime = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  );
};

const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : '0' + n;
};

//获取年份
const getYears = n => {
  let years = [];
  n = n == undefined ? 6 : n;
  let date = new Date();
  const year = date.getFullYear();
  years.push('');
  for (let i = 0; i < n; i++) {
    if (i == n) {
      let year_name = year - (i - 1) + '';
      years.push(year_name + '-1');
    } else {
      years.push(year - i);
    }
  }
  return years;
};

const objectToUrlParams = obj => {
  var str = '';
  for (var key in obj) {
    str += '&' + key + '=' + obj[key];
  }
  return str.substr(1);
};

const sortStr = arr => {
  return arr.sort(function compareFunction(item1, item2) {
    return item1.localeCompare(item2);
  });
};

//获取直播视频地址
const getResetVideo = url => {
  return url.replace('.mp4', '/default.m3u8');
};

const course_arr = ['地理', '生物', '政治', '历史', '物理', '化学'];

//过滤年级对应的学科
const getCourses = grades => {
  grades.map(grade => {
    let g_id = grade.grade_id.toString().substr(0, 1);
    if (g_id == '1') {
      //小学
      let courses = grade.course_list;
      course_arr.map(item => {
        courses.splice(
          courses.findIndex(course => course.course_name == item),
          1
        );
      });
      grade.course_list = courses;
    }
  });
  return grades;
};

//获取指定时间距离当前时间的秒数
const getTimeStampDiff = start_date => {
  let date = start_date.replace(/-/g, '/');
  var current_timestamp = parseInt(new Date().getTime() / 1000);
  let timestamp = parseInt(new Date(date).getTime() / 1000);
  let second = current_timestamp - timestamp;
  return second;
};

//获取指定时间+30分钟后的时间
const getTimePlusOneHalfHour = start_date => {
  let date = start_date.replace(/-/g, '/');
  let deadline_stamp = parseInt(new Date(date).getTime() / 1000) + 1800;
  return formatTime(new Date(deadline_stamp * 1000));
};

// 计算距离今天的天数
const dateDiff = sDate1 => {
  var dateSpan, tempDate, iDays, sDate2;
  sDate1 = Date.parse(sDate1);
  sDate2 = Date.parse(new Date());
  dateSpan = sDate2 - sDate1;
  dateSpan = Math.abs(dateSpan);
  iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
  return iDays;
};

var chnNumChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
var chnUnitSection = ['', '万', '亿', '万亿', '亿亿'];
var chnUnitChar = ['', '十', '百', '千'];

const SectionToChinese = section => {
  var strIns = '',
    chnStr = '';
  var unitPos = 0;
  var zero = true;
  while (section > 0) {
    var v = section % 10;
    if (v === 0) {
      if (!zero) {
        zero = true;
        chnStr = chnNumChar[v] + chnStr;
      }
    } else {
      zero = false;
      strIns = chnNumChar[v];
      strIns += chnUnitChar[unitPos];
      chnStr = strIns + chnStr;
    }
    unitPos++;
    section = Math.floor(section / 10);
  }
  return chnStr;
};

const NumberToChinese = num => {
  var unitPos = 0;
  var strIns = '',
    chnStr = '';
  var needZero = false;

  if (num === 0) {
    return chnNumChar[0];
  }

  while (num > 0) {
    var section = num % 10000;
    if (needZero) {
      chnStr = chnNumChar[0] + chnStr;
    }
    strIns = SectionToChinese(section);
    strIns += section !== 0 ? chnUnitSection[unitPos] : chnUnitSection[0];
    chnStr = strIns + chnStr;
    needZero = section < 1000 && section;
    num = Math.floor(num / 10000);
    unitPos++;
  }

  return chnStr;
};

module.exports = {
  post,
  get,
  getRequestPromisified,
  formatTime: formatTime,
  getYears: getYears,
  sortStr: sortStr,
  NumberToChinese: NumberToChinese,
  getResetVideo: getResetVideo,
  objectToUrlParams: objectToUrlParams,
  formatDate: formatDate,
  teacherTagStyles: teacherTagStyles,
  getCourses: getCourses,
  dateDiff: dateDiff,
  getTimeStampDiff: getTimeStampDiff,
  getTimePlusOneHalfHour: getTimePlusOneHalfHour
};
